<template>
  <div>
    <el-form
      ref="deptForm"
      :model="form"
      :rules="fromRules"
      label-width="120px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees' // 员工管理
import {
  addDepartments,
  getDepartmentsDetail,
  editDepartments
} from '@/api/departments' // 组织架构
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 判断部门编码code是否重复
    const vaildCode = (rule, value, callback) => {
      console.log(
        'originList中所有code',
        this.originList.map((item) => item.code)
      )
      let exiseCodeList = this.originList.map((item) => item.code) // 筛选出originList中所有code
      if (this.isEdit) {
        // filter排除this.id 自己的那一个数据
        exiseCodeList = this.originList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code)
      }

      exiseCodeList.includes(value)
        ? callback(new Error('部门编码已存在'))
        : callback()
    }
    // 部门名称在同级中不允许重复
    const vaildName = (rule, value, callback) => {
      let exiseNameList = this.originList
        .filter((item) => item.pid === this.id)
        .map((item) => item.name)
      // 通过当前id找父级在找出所有的子级(包括自己)再排除自己
      if (this.isEdit) {
        const pid = this.originList.find((item) => item.id === this.id).pid // 找父级的pid
        exiseNameList = this.originList
          .filter((item) => item.pid === pid) // 找到所有兄弟 包括自己
          .filter((item) => item.id !== this.id) // 所有兄弟 排除自己
          .map((item) => item.name) // map映射自己name的数组
      }
      exiseNameList.includes(value)
        ? callback(new Error('此部门名在同级部门中已存在'))
        : callback()
    }
    return {
      // 表单数据项
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 表单校验规则
      fromRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门名称', trigger: 'blur' },
          { validator: vaildName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门名称', trigger: 'blur' },
          { validator: vaildCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: 'blur'
          }
        ]
      },
      employees: [] // 存储下拉框数据
    }
  },
  created() {
    this.loadEmployeeSimple()
    if (this.isEdit) {
      // isEdit为true 弹框为编辑框
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    // 确定
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.duEdit() : this.doAdd() // 三元
      })
    },
    // 取消
    hCancel() {
      this.$emit('success')
    },
    // 发送请求获取单位负责人信息
    async loadEmployeeSimple() {
      const res = await getEmployeeSimple()
      // console.log('employees数组:', res.data)
      this.employees = res.data
    },
    // 添加部门
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res)
        // 添加成功 触发父组件close事件
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 根据id获取部门详情
    async loadDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        console.log('根据id获取部门详情', res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async duEdit() {
      try {
        const res = await editDepartments({ id: this.id, ...this.form })
        console.log('编辑部门', res)
        // 编辑成功 触发父组件close事件
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style></style>
